class buildToc {
    constructor(selector, tags, prefix) {
        this.headings = document.getElementById(selector).querySelectorAll(tags);
        this.prefix = prefix;
    }
    getTree() {
        let currentNode = null;
        const rootNodes = [];
        for (const heading of this.headings) {
            const { id, tagName, textContent } = heading;
            const level = parseInt(tagName.slice(1));

            if (!currentNode || level <= currentNode.level) {

                currentNode = new TreeNode(id, tagName, textContent, level, heading, this.prefix);

                rootNodes.push(currentNode);

            } else {
                // 添加节点前，检查是否已存在相同级别的节点且其子节点中不存在相同文本内容的节点
                let isDuplicate = false;
                for (const child of currentNode.children) {
                    if (child.level === level && child.text === textContent) {
                        isDuplicate = true;
                        break;
                    }
                    if (child.children.some(grandChild => grandChild.level === level && grandChild.text === textContent)) {
                        isDuplicate = true;
                        break;
                    }
                }

                if (!isDuplicate) {
                    // 修正：当新节点层级大于当前节点层级时，向上寻找合适的父节点
                    let foundParent = false;
                    let parent = null;

                    while (level > currentNode.level && !foundParent) {
                        parent = currentNode;
                        if (parent.parent) {
                            currentNode = parent.parent;
                        } else {
                            foundParent = true;
                        }
                    }

                    if (parent) {
                        // 将新节点添加到找到的合适父节点下
                        parent.children.push(new TreeNode(id, tagName, textContent, level, heading, this.prefix));
                    } else {
                        console.warn('Unable to find a suitable parent node for the current heading. The heading will be ignored.');
                    }
                }
            }
        }
        return rootNodes;
    }
}

class TreeNode {
    constructor(id, tagName, text, level, heading, prefix) {
        if (!id) {
            id = prefix + Math.random().toString(16).substr(2, 9);
            heading.id = id;
        }

        this.id = id;
        this.tagName = tagName;
        this.text = text;
        this.level = level;
        this.children = [];
    }
}